package com.gj.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gj.reggie.common.CustomException;
import com.gj.reggie.dto.SetmealDto;
import com.gj.reggie.entity.Setmeal;
import com.gj.reggie.entity.SetmealDish;
import com.gj.reggie.mapper.SetmealMapper;
import com.gj.reggie.service.SetMealDishService;
import com.gj.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author 郭嘉
 * @date 2022/12/29 - 16:12
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetMealDishService setMealDishService;

    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐基本信息
        this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        setmealDishes=setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        //保存对应菜品关联信息
        setMealDishService.saveBatch(setmealDishes);
    }

    @Override
    @Transactional
    public void removeWithDish(List<Long> list) {
        //查询套餐状态是否可以删除
        LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.in(Setmeal::getId,list);
        queryWrapper.eq(Setmeal::getStatus,1);
        int count = this.count(queryWrapper);
        if(count>0){
            //不能删除的话，抛出异常
            throw new CustomException("套餐正在售卖出，不能删除");
        }
        //如果可以删除，先删除套餐表中数据
        this.removeByIds(list);
        //删除关系中的数据
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getDishId,list);

        setMealDishService.remove(lambdaQueryWrapper);
    }

    @Override
    public void updateSetMealStatus(Integer status, Long[] ids) {

        List<Long> collect = Arrays.stream(ids).collect(Collectors.toList());
        LambdaUpdateWrapper<Setmeal> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();

        lambdaUpdateWrapper.set(Setmeal::getStatus,status);
        lambdaUpdateWrapper.in(Setmeal::getId,collect);

        this.update(lambdaUpdateWrapper);

    }
}
